from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
import uvicorn
from pathlib import Path

from plugin_system.plugin_manager import PluginManager
from plugin_system.routes import router as plugin_router

# 创建FastAPI应用
app = FastAPI(
    title="FastAPI插件系统",
    description="一个基于FastAPI的插件管理系统",
    version="1.0.0"
)

# 设置静态文件和模板
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")

# 初始化插件管理器
plugin_manager = PluginManager()

# 注册插件路由
app.include_router(plugin_router, prefix="/api/plugins")

# 注册插件提供的路由
for plugin_name, plugin in plugin_manager.plugins.items():
    if hasattr(plugin, 'router'):
        app.include_router(plugin.router)
        print(f"已注册插件路由: {plugin_name}")

@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
    """主页"""
    return templates.TemplateResponse(
        "index.html", 
        {"request": request, "title": "FastAPI插件系统"}
    )

@app.get("/plugins", response_class=HTMLResponse)
async def plugins_page(request: Request):
    """插件管理页面"""
    plugins = plugin_manager.get_all_plugins()
    return templates.TemplateResponse(
        "plugins.html", 
        {"request": request, "plugins": plugins, "title": "插件管理"}
    )

@app.get("/dashboard", response_class=HTMLResponse)
async def dashboard(request: Request):
    """仪表板页面"""
    active_plugins = plugin_manager.get_active_plugins()
    return templates.TemplateResponse(
        "dashboard.html", 
        {"request": request, "active_plugins": active_plugins, "title": "仪表板"}
    )

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) 